using AutoMapper;
using MediatR;
using RBAC.Domain.SmartHealthcare;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using SmartHealthcare.Read.Api.Application.Command.Case;
using SmartHealthcare.Read.Api.DTo;

namespace SmartHealthcare.Read.Api.Application.Handler.Case
{
    /// <summary>
    /// 根据科室ID获取病例列表处理器
    /// </summary>
    public class GetCasesByDepartmentHandler : IRequestHandler<GetCasesByDepartmentCommand, APIResult<List<CaseDto>>>
    {
        private readonly IBaseRepository<CaseModel> _caseRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<GetCasesByDepartmentHandler> _logger;

        public GetCasesByDepartmentHandler(
            IBaseRepository<CaseModel> caseRepository, 
            IMapper mapper, 
            ILogger<GetCasesByDepartmentHandler> logger)
        {
            _caseRepository = caseRepository;
            _mapper = mapper;
            _logger = logger;
        }

        public Task<APIResult<List<CaseDto>>> Handle(GetCasesByDepartmentCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<CaseDto>> res = new APIResult<List<CaseDto>>();
            
            try
            {
                // 根据科室ID获取该科室下的所有未删除病例
                var cases = _caseRepository.GetALL()
                    .Where(x => x.IsDeleted == false && x.DepartmentId == request.DepartmentId)
                    .ToList();

                // 使用AutoMapper进行映射
                var caseDtos = _mapper.Map<List<CaseDto>>(cases);

                res.Data = caseDtos;
                res.Code = APIEnums.Success;
                res.Msg = "查询成功";
                _logger.LogInformation("根据科室ID {DepartmentId} 查询病例成功，共查询到 {Count} 条记录", 
                    request.DepartmentId, caseDtos.Count);
                
                return Task.FromResult(res);
            }
            catch (Exception ex)
            {
                res.Code = APIEnums.Fail;
                res.Msg = "查询失败";
                res.Data = new List<CaseDto>();
                _logger.LogError(ex, "根据科室ID {DepartmentId} 查询病例失败", request.DepartmentId);
                
                return Task.FromResult(res);
            }
        }
    }
}
